#include "GameWindow.h"

#include <QMetaEnum>
#include <QMessageBox>

GameWindow::GameWindow(QTcpSocket* socket)
    : socket(socket)
{
    setWindowTitle("你画我猜");
    setAttribute(Qt::WA_DeleteOnClose);

    connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(socket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(onErrorOccurred(QAbstractSocket::SocketError)));
}

void GameWindow::closeEvent(QCloseEvent* event)
{
    socket->close();
    this->hide();
    emit closed();
}

void GameWindow::onReadyRead()
{
    auto msg = QString(socket->readAll());
    auto args = msg.split(' ');

    if (args[0] == "FINISH") {
        close();
    }
}

void GameWindow::onErrorOccurred(QAbstractSocket::SocketError error)
{
    QMetaEnum e = QMetaEnum::fromType<QAbstractSocket::SocketError>();
    QMessageBox::critical(this, "错误", QString("网络错误 (错误信息：%0）").arg(e.valueToKey(error)));

    this->close();
}
